function initChart(canvas, width, height, dpr) {
    const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
    });
    canvas.setChart(chart);

    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: '{b}: {c}mmol/L'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['1/4', '1/24', '1/31', '2/4', '2/14', '2/18', '3/1'],
            axisLine: {
                lineStyle: {
                    color: '#999'
                }
            },
            axisLabel: {
                color: '#666'
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    color: '#eee',
                    type: 'dashed'
                }
            },
            axisLabel: {
                color: '#666'
            }
        },
        series: [{
            data: [4.1, 4.1, 5.1, 5.6, 6.0, 5.4, 3.7],
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
                color: '#4169E1'
            },
            lineStyle: {
                color: '#4169E1',
                width: 3
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(65,105,225,0.3)'
                    }, {
                        offset: 1,
                        color: 'rgba(65,105,225,0)'
                    }]
                }
            }
        }]
    };

    chart.setOption(option);
    return chart;
}
import request from '../../../../utils/request'
Page({
    data: {
        ec: {
            onInit: initChart
        },
        currentDate: '2021年3月1日 14:00',
        suger: '9.6',
        sugerStatus: '餐后 偏高',
        timeType: 'before',
        showModal: false,
        inputSuger: '',
        sugerRecords: [{
            id: 1,
            date: '2020/01/24',
            time: '10:56',
            value: '4.2',
            status: '正常'
        }]
    },

    onLoad: function () {
        this.getBloodSuger()
            .then(bloodsuger => {
                this.setData({
                    bloodsuger: bloodsuger
                })
            })
    },
    //获取用户血糖
    getBloodSuger() {
        return new Promise((resolve, reject) => {
            let userId = wx.getStorageSync('userid')
            let bloodsugerid = 2 //数据库中血糖id=2
            let url = `healthlog/healthlog/selectByUseridAndTypeid?userid=${userId}&typeid=${bloodsugerid}`
            request({
                url: url,
                method: 'GET',
                success(res) {
                    // console.log("血糖列表：",res.data);
                    let bloodsuger = res.data
                    resolve(bloodsuger)
                },
                fail(error) {
                    reject(error)
                }
            })
        })
    },
    goBack: function () {
        wx.navigateBack({
            delta: 1
        });
    },

    switchType: function (e) {
        const type = e.currentTarget.dataset.type;
        this.setData({
            timeType: type
        });
        // 这里可以根据类型切换图表数据
    },

    showSugerModal: function () {
        this.setData({
            showModal: true,
            inputSuger: ''
        });
    },

    hideModal: function () {
        this.setData({
            showModal: false
        });
    },

    onSugerInput: function (e) {
        this.setData({
            inputSuger: e.detail.value
        });
    },

    saveSuger: function () {
        // 检查输入的血糖值是否为空
        if (!this.data.inputSuger) {
            
            wx.showToast({
                title: '请输入血糖值',
                icon: 'none'
            });
            return;
        }

        // 获取输入的血糖值，并转换为数值类型
        const bloodsuger = parseInt(this.data.inputSuger);

        // 获取当前时间并格式化为 YYYY-MM-DD HH:mm:ss 的形式
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

        // 从本地存储中获取当前用户的 ID
        const userId = wx.getStorageSync('userid');

        // 构建要插入数据库的血糖记录对象
        const record = {
            number: bloodsuger, // 血糖数值
            typeid: 2, // 血糖类型 ID，固定值为 3
            time: formattedTime, // 当前时间
            source: 1, // source 字段，固定值为 1
            userId: userId // 当前用户的 ID
        };

        // 定义数据库插入接口的 URL
        let url = `healthlog/healthlog`;
        // 发送 POST 请求将数据插入数据库
        request({
            url: url,
            method: 'POST',
            data: record,
            success: (res) => {
                // 插入成功时的处理逻辑
                console.log("血糖数据插入成功", res.data);
                wx.showToast({
                    title: '保存成功',
                    icon: 'success'
                });
                // 插入成功后重新获取血糖列表
                this.getBloodSuger()
                    .then(bloodsuger => {
                        this.setData({
                            bloodsuger: bloodsuger
                        });
                        // 获取成功后关闭弹窗并清空输入框
                        this.setData({
                            showModal: false,
                            inputSystolic: ''
                        });
                    })
                    .catch(error => {
                        console.error("获取血糖列表失败", error);
                        wx.showToast({
                            title: '获取血糖数据失败',
                            icon: 'none'
                        });
                    });
            },
            fail: (error) => {
                // 插入失败时的处理逻辑
                console.error("血糖数据插入失败", error);
                wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                });
            }

        });
    },

    getSugerStatus: function (value) {
        if (value < 3.9) return '偏低';
        if (value > 7.8) return '偏高';
        return '正常';
    },

    editSuger: function (e) {
        const id = e.currentTarget.dataset.id;
        const record = this.data.sugerRecords.find(item => item.id === id);
        if (record) {
            this.setData({
                showModal: true,
                inputSuger: record.value
            });
        }
    },

    deleteSuger: function (e) {
        const id = e.currentTarget.dataset.id;
        wx.showModal({
            title: '提示',
            content: '确定要删除这条记录吗？',
            success: res => {
                if (res.confirm) {
                    const sugerRecords = this.data.sugerRecords.filter(item => item.id !== id);
                    this.setData({
                        sugerRecords
                    });
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    });
                }
            }
        });
    }
});